package bigo.todolist.avocado;

/** 
 * TaskList class
 * @author Big Ohvocodo Task Force
 */

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class TaskList extends Activity implements OnClickListener{ 
	
	ImageButton addTask;
	ImageButton mapTask;
	String username;
	String currentCat;
	String[] taskList;
	String[] catList;
	ListView myList;
	Spinner spinner;
	ArrayList<String> checks = new ArrayList<String>();
	ArrayAdapter<CharSequence> adapter;
	private TextView dateLabel;
	private ImageButton changeDateButton;
	private String myDate;
	private int date;
	ImageButton mapsButton;
	DBTaskAdapter dbTask;
	DBCategoryAdapter dbCat;
	
	private int year;
	private int month;
	private int day;
	
	static final int DATE_DIALOG_ID = 1;
	
	protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.tasklist); //Set the layout of the window
			initialize();
			
			Bundle recieveUsername = getIntent().getExtras();
			if(recieveUsername != null)
			{
				username = recieveUsername.getString("username");
			}
			else
			{
				username = "test4";
			}

			restructure("All");
			
			
			addTask.setOnClickListener(this);
			mapTask.setOnClickListener(this);
			spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
			changeDateButton.setOnClickListener(this);
			mapsButton.setOnClickListener(this);
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}
	
	/**
	 * Initialize all interactive widgets
	 */
	private void initialize() {
		addTask = (ImageButton) findViewById(R.id.addButton);
		mapTask = (ImageButton) findViewById(R.id.mapsButton);
		myList= (ListView)findViewById(R.id.mylist);
		spinner = (Spinner) findViewById(R.id.catspinner);
		changeDateButton = (ImageButton) findViewById(R.id.changeDateButton);
		dateLabel = (TextView) findViewById(R.id.dateLabel);
		mapsButton = (ImageButton) findViewById(R.id.mapsButton);
		
		//initialize date stuff
		final Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);
	}
	
	/**
	 * Method that sums up all that is done to generate the original tasklist and spinner
	 * @param category
	 */
	public void restructure(String category)
	{
		dbTask = new DBTaskAdapter(TaskList.this);
		dbCat = new DBCategoryAdapter(TaskList.this);
		dbTask.open();
		taskList = dbTask.getTask(username, category);
		dbTask.close();
		dbCat.open();
		catList = dbCat.getCategory(true);
		dbCat.close();
		
		currentCat = "All";
		
		ArrayAdapter <CharSequence> adapter = new ArrayAdapter <CharSequence> (this, android.R.layout.simple_spinner_item );
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    for(int i = 0; i<catList.length; i++)
	    {
	    	adapter.add(catList[i]);
	    }
	    spinner.setAdapter(adapter);
		ArrayAdapter<Model> taskAdapter = new InteractiveArrayAdapter(this, getModel(), username, checks);
		myList.setAdapter(taskAdapter);
		
	}
	
	/**
	 * Method for setting/updating the task list from a newly queried task list
	 * @param newList
	 */
	public void setTaskAdapter(String[] newList)
	{
		taskList = newList;
		
		//DBTaskAdapter dbTask = new DBTaskAdapter(TaskList.this);
		
		//List<Model> newModel = getModel();
		
		ArrayAdapter<Model> taskAdapter = new InteractiveArrayAdapter(this, getModel(), username, checks);
		myList.setAdapter(taskAdapter);
		getCoordinates();
		
	}
	
	/**
	 * Test to see if the task list going into the adapter is null
	 * @param testList
	 * @return
	 */
	public boolean taskAdapterProcedure(String[] testList){ 
		if (testList == null){
			return false;
		}
		return true;
	}
	
	/**
	 * Create a model and check if whether the task within it should be checked or not
	 * @return
	 */
	private List<Model> getModel() {
		List<Model> list = new ArrayList<Model>();
		int index = 0;
		for (String s: taskList) { //Adds every task queried to the task list model.
			list.add(get(s));
			if(checks.contains(s)) //Checks to see if task should be checked or not. Checks contains which tasks should be checked
			{
				list.get(index).setSelected(true); //If task is in checks, it shall be checked
			}
			index++;
		}
		return list;
	}

	/**
	 * Generate a with given parameter
	 * @param s
	 * @return
	 */
	private Model get(String s) {
		return new Model(s);
	}
	
	/**
	 * Set up onclick listener cases
	 * @param view
	 */
	public void onClick(View view) {
		switch(view.getId())
		{
			case R.id.addButton: //Case for add button
				Intent ourIntent = new Intent(TaskList.this, addATask.class);
				Bundle sendUsername = new Bundle(); //Prepare bundle with user name and jump to add a task acitivty
				sendUsername.putString("username", username);
				ourIntent.putExtras(sendUsername);
				startActivity(ourIntent);
				break;
				
			case R.id.mapsButton: //Case for maps button
				Intent intent = new Intent();
                intent.setClass(TaskList.this, TaskMapActivity.class); //Prepare task list, description, and coordinate bundle
                Bundle sendTaskList = new Bundle();
                sendTaskList.putStringArray("taskNameList", getTaskList());
                sendTaskList.putStringArray("taskDescriptionList", getDescription());
                sendTaskList.putDoubleArray("taskLocList", getCoordinates());
                intent.putExtras(sendTaskList);
                startActivity(intent); //Start maps the activity
                break;
				
			case R.id.changeDateButton: //Case for date button
				showDialog(DATE_DIALOG_ID); //Show the date dialog
				break;
				
		}
	}
	
	/**
	 * Method for setting buttons of the menu that appears at the bottom of the screen
	 * @param item
	 * @return
	 */
	public boolean onOptionsItemSelected(MenuItem item)
	{
	    switch (item.getItemId())
	    {
	        case R.id.about: //Case for pressing about
	             //To be determined
	             return true;
	        case R.id.logout: //Case for pressing logout
	        	Intent logoutIntent = new Intent(TaskList.this, Login.class);
				startActivity(logoutIntent); //Goes back to login screen
	             return true;
	    }
	  return false;
	}


	
	/**
	 * Method for setting up dialog box of date
	 * @param id
	 * @return
	 */
	protected Dialog onCreateDialog(int id) {
		switch(id) {
			case DATE_DIALOG_ID:
				//set selected date as current date
				return new DatePickerDialog(this,datePickerListener, year, month,day);
		}
		return null;
	}
	
	/**
	 * Set up the task last depending on what date was chosen in the date dialog box
	 */
	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
		
		// this method is called when the date picker dialog box is closed
		public void onDateSet(DatePicker view, int selectedYear, int selectedMonth,
				int selectedDay) {
			//Prepare date
			year = selectedYear;
			month = selectedMonth+1;
			day = selectedDay;
			String space ="";
			if(Integer.valueOf(day) < 10)
				space = "0";
			
			//set selected date to text view
			dateLabel.setText(new StringBuilder().append("Displaying tasks due after: ").append(month)
					   .append("-").append(day).append("-").append(year)
					   .append(" ")); //Display what date was selected
			myDate = ""+year + month + space + day; //Prepare date to be placed in database

			DBTaskAdapter dbTask = new DBTaskAdapter(TaskList.this);
			dbTask.open();
			taskList = dbTask.getTask(username, currentCat, myDate); //Get tasks depending on date
			dbTask.close();
			
			setTaskAdapter(taskList); //Set task list
		}
	};

	/**
	 * Runs a task list query depending on what category was selected from the spinner
	 * @author Alex Irlik
	 *
	 */
	public class MyOnItemSelectedListener implements OnItemSelectedListener {
	    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
	    {
	    	DBTaskAdapter dbTask = new DBTaskAdapter(TaskList.this);
	    	DBCategoryAdapter dbCat = new DBCategoryAdapter(TaskList.this);
			dbTask.open();
			if((parent.getItemAtPosition(pos).toString().compareTo("Completed") == 0) || (parent.getItemAtPosition(pos).toString().compareTo("Uncompleted") == 0))
				taskList = dbTask.getTask(username, parent.getItemAtPosition(pos).toString(), checks); //If uncompleted/completed runs a special checks query
			else
				taskList = dbTask.getTask(username, parent.getItemAtPosition(pos).toString()); //Otherwise runs query with a category restriction
			dbTask.close();
			dbCat.open();
			catList = dbCat.getCategory(true); //Get the category list. All categories will be displayed!
			dbCat.close();
			
			setTaskAdapter(taskList); //Set the task list with the new task list query
			
			currentCat = parent.getItemAtPosition(pos).toString(); //Select query selected
			
	    	Toast.makeText(parent.getContext(), "The category selected is " + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show(); //Alert on what category was selected
	    }
	    
	    /**
	     * Do nothing
	     */
	    public void onNothingSelected(AdapterView parent) {
	      // Do nothing.
	    }
	}
	
	/**
	 * Get username
	 * @return
	 */
	public String getUsername()
	{
		return username;
	}
	
	/**
	 * Set username
	 * @param user
	 */
	public void setUsername(String user)
	{
		username = user;
	}
	
	/**
	 * Get category list
	 * @return
	 */
	public String[] getCatList()
	{
		return catList;
	}
	
	/**
	 * Get the category database instance
	 * @return
	 */
	public DBCategoryAdapter getDBCat()
	{
		return dbCat;
	}
	
	/**
	 * Get the task database instance
	 * @return
	 */
	public DBTaskAdapter getDBTask()
	{
		return dbTask;
	}
	
	/**
	 * Get all descriptions of tasks
	 * @return
	 */
	public String[] getDescription() {
		DBTaskAdapter dbTask = new DBTaskAdapter(TaskList.this);
		dbTask.open();
		String[] aStr = dbTask.getDescription(username); //Run description query to get all descriptions
		dbTask.close();
		
		
		return aStr;
	}
	
	/**
	 * Get coordinates of all tasks
	 * @return
	 */
	public double[] getCoordinates() {
		DBTaskAdapter dbTask = new DBTaskAdapter(TaskList.this);
		dbTask.open();
		double[] result = dbTask.getCoordinates(username); //Run query to get all coordinates into an array
		dbTask.close();
		
		return result;
	}
	
	/**
	 * Get the task list list of names
	 * @return
	 */
	public String[] getTaskList(){
		return taskList;
	}
	
	/**
	 * Set the task list list of names
	 * @param a
	 */
	public void setTaskList(String[] a){
		taskList = a;
	}
	
	/**
	 * Get which tasks are checked
	 * @return
	 */
	public ArrayList<String> getChecks(){
		return checks;
	}
	
	/**
	 * Set the list of checks
	 * @param a
	 */
	public void setChecks(ArrayList<String> a){
		checks = a;
	}

}
